package cn.song.config.convert;

import cn.song.constants.enums.GenderEnum;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import lombok.extern.slf4j.Slf4j;

/**
 * Excel 枚举类型装换器
 *
 * @author wang suo
 * @version 1.0
 * @date 2021/9/14 15:06
 */
@Slf4j
public class BaseEnumTypeConverter implements Converter<GenderEnum> {

    /**
     * 转换为 Java 数据
     *
     * @param cellData            单元格数据
     * @param contentProperty     content 属性
     * @param globalConfiguration 全局配置
     * @return {@link GenderEnum }
     * @date 2025/01/20
     * @author SongRenShuo
     */
    @Override
    public GenderEnum convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        try {
            CellDataTypeEnum type = cellData.getType();
            if (CellDataTypeEnum.NUMBER.equals(type)){
                return GenderEnum.valueOf(cellData.getNumberValue().intValue());
            } else if (CellDataTypeEnum.STRING.equals(type)) {
                return GenderEnum.valueOfName(cellData.getStringValue());
            }

            return null;
        } catch (NumberFormatException e) {
            log.error("Excel 枚举类型装换器 转换失败,当前值：{}",cellData.getOriginalNumberValue(), e);
            return null;
        }
    }


    /**
     * 转换为 Excel 数据
     *
     * @param genderEnum          性别枚举
     * @param contentProperty     content 属性
     * @param globalConfiguration 全局配置
     * @return {@link WriteCellData }<{@link ? }>
     * @date 2025/01/20
     * @author SongRenShuo
     */
    @Override
    public WriteCellData<?> convertToExcelData(GenderEnum genderEnum, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        // 将枚举类型按照 key 传值
        return new WriteCellData<>(genderEnum.getName());
    }
}
